package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class ContactTeamController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def contactTeamList = ContactTeam.findAll("from ContactTeam where user.username = '${username}'", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = ContactTeam.executeQuery("select count(id) from ContactTeam where user.username = '${username}'")

        respond contactTeamList, model: [contactTeamCount: count[0]]
    }

    def show(ContactTeam contactTeam)
    {
        respond contactTeam
    }

    def create()
    {
        def contact = Contact.findById(params['contact'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (contact?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def contactTeams = ContactTeam.findAllByContact(contact)
            contactTeams?.each {
                userList -= it?.user
            }
            respond new ContactTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "contact", action: "show", params: [id: contact.id])
            return
        }
    }

    @Transactional
    def save(ContactTeam contactTeam)
    {
        if (contactTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contactTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contactTeam.errors, view: 'create'
            return
        }

        contactTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contactTeam.label', default: 'ContactTeam'), contactTeam.id])
                // redirect contactTeam
                redirect(controller: "contact", action: "show", params: [id: contactTeam?.contact?.id])
            }
            '*' { respond contactTeam, [status: CREATED] }
        }
    }

    def edit(ContactTeam contactTeam)
    {
        respond contactTeam
    }

    @Transactional
    def update(ContactTeam contactTeam)
    {
        if (contactTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contactTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contactTeam.errors, view: 'edit'
            return
        }

        contactTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'contactTeam.label', default: 'ContactTeam'), contactTeam.id])
                // redirect contactTeam
                redirect(controller: "contact", action: "show", params: [id: contactTeam?.contact?.id])
            }
            '*' { respond contactTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(ContactTeam contactTeam)
    {

        if (contactTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (contactTeam?.contact?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            contactTeam.delete flush: true
            request.withFormat {
                form multipartForm {
                    flash.message = message(code: 'default.deleted.message', args: [message(code: 'contactTeam.label', default: 'ContactTeam'), contactTeam.id])
                    // redirect action:"index", method:"GET"
                    redirect(controller: "contact", action: "show", params: [id: contactTeam?.contact?.id])
                }
                '*' { render status: NO_CONTENT }
            }
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "contact", action: "show", params: [id: contactTeam?.contact.id])
            return
        }

    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'contactTeam.label', default: 'ContactTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchContactTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]

        String sql = "from ContactTeam as o where 1 = 1 and o.user.username = '${username}'"
        if (fullName)
        {
            sql += " and o.contact.fullName like '%${fullName}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and o.contact.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(o.id) " + sql
        sql += ' order by o.createdDate desc'

        def list = ContactTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = ContactTeam.executeQuery(countSql)

        respond list, model: [contactTeamCount: count, params: params], view: 'index'
    }

    def exportContactTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]

        String sql = "from ContactTeam as o where 1 = 1 and o.user.username = '${username}'"
        if (fullName)
        {
            sql += " and o.contact.fullName like '%${fullName}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and o.contact.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(o.id) " + sql
        sql += ' order by o.createdDate desc'

        def list = ContactTeam.findAll(sql)
        def count = ContactTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=contactTeam.${params.extension}")
            List fields = ["contact.fullName", "contact.user.fullName", "contact.salutation.name", "contact.title", "contact.job", "contact.email", "contact.fax", "contact.phone", "contact.cellphone", "contact.wechat", "contact.qq", "contact.birthday", "contact.hometown", "contact.hobby", "contact.taboo", "contact.country.name", "contact.city.name", "contact.idNumber", "contact.maritalStatus", "contact.gender", "contact.source.name", "contact.cellphoneHasVerified", "contact.active", "contact.account.name", "contact.lead.fullName", "contact.type.name", "contact.level.name", "contact.hireDate", "contact.leaveDate", "contact.createdDate", "contact.modifiedDate"]
            Map labels = ["contact.fullName": "姓名", "contact.user.fullName": "所有者", "contact.salutation.name": "称谓", "contact.title": "头衔", "contact.job": "职务", "contact.email": "邮箱", "contact.fax": "传真", "contact.phone": "座机", , "contact.cellphone": "手机", "contact.wechat": "微信", "contact.qq": "QQ", "contact.birthday": "生日", "contact.hometown": "家乡", "contact.hobby": "爱好", "contact.taboo": "禁忌", "contact.country.name": "国籍", "contact.city.name": "城市", "contact.idNumber": "身份证号", "contact.maritalStatus": "婚姻状况", "contact.gender": "性别", "contact.source.name": "联系人来源", "contact.cellphoneHasVerified": "手机已验证", "contact.active": "是否激活", "contact.account.name": "客户", "contact.lead.fullName": "线索", "contact.type.name": "联系人类型", "contact.level.name": "联系人分级", "contact.hireDate": "入职时间", "contact.leaveDate": "离职时间", "contact.createdDate": "创建时间", "contact.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
